var latitude;
var longitude;

var action;

function setCoordinates(lati, longi) {
    longitude = longi;
    latitude = lati;
}

window.onload = function() {
    $('#home').keyup();
}

$(document).ready(function() {
    var namePattern = "^[a-zA-Z][\\w\\s]{1,}$";
    var nameTip = $("#nameTip");
    var name = $('#name_group');

    name.keyup(function() {
        checkValidate(name, nameTip, namePattern);
    });
    
    $('#left-big-arrow').unbind('click').click(function() {
        var group_users = $('#group_users option');
        var new_group_users = $('#non_group_users :selected');
        var htmlStr = $('#group_users').html();
        for (var i = 0; i < new_group_users.length; i++) {
            var flag = true;
            for (var j = 0; j < group_users.length; j++) {
                if ($(group_users[j]).attr('id') == $(new_group_users[i]).attr('id')) {
                    flag = false;
                }
            }
            if (flag) {
                htmlStr += '<option id=';
                htmlStr += '"' + $(new_group_users[i]).attr('id') + '" >';
                htmlStr += $(new_group_users[i]).html();
                htmlStr += '</option>';
            }
        }
        $('#group_users').html(htmlStr);

        var non_group_users = $('#non_group_users option');
        htmlStr = '';
        for (var i = 0; i < non_group_users.length; i++) {
            var flag = true;
            for (var j = 0; j < new_group_users.length; j++) {
                if ($(non_group_users[i]).attr('id') == $(new_group_users[j]).attr('id')) {
                    flag = false;
                }
            }
            if (flag) {
                htmlStr += '<option id=';
                htmlStr += '"' + $(non_group_users[i]).attr('id') + '" >';
                htmlStr += $(non_group_users[i]).html();
                htmlStr += '</option>';
            }
        }
        $('#non_group_users').html(htmlStr);
    });

    $('#right-big-arrow').unbind('click').click(function() {
        var group_users = $('#group_users option');
        var htmlStr = "";
        for (var i = 0; i < group_users.length; i++) {
            if (!$(group_users[i]).is(":selected")) {
                htmlStr += '<option id=';
                htmlStr += '"' + $(group_users[i]).attr('id') + '" >';
                htmlStr += $(group_users[i]).html();
                htmlStr += '</option>';
            }
        }
        $('#group_users').html(htmlStr);
        filter_role();
    });

    $("#save_group").unbind('click').click(function() {
        if (!checkValidate(name, nameTip, namePattern)) {
            return;
        }        
        var nameGroup = $('#name_group').val();
        var roleGroup = null;
        if ($('#apply').is(":checked")) {
            roleGroup = $('#select_group_role :selected').attr('id');
        }
        var group_users = $('#group_users option');       
        var users = "users=";
        for (var i = 0; i < group_users.length; i++) {
            users += $(group_users[i]).attr('id');
            if (i != group_users.legth - 1) {
                users += ';';
            }
        }
        var dataString = "action=";   
        var idGroup = $('#group_id').attr('value');
        if (idGroup == null) {
            dataString += "create";
        } else {
            dataString += "change&group=" + idGroup;
        }
        dataString += "&name=" + nameGroup;
        if (roleGroup != null) {
            dataString += "&role=" + roleGroup;
        }
        dataString += "&" + users;
        sendData(dataString, "GroupOperation", function() {
            window.location.replace('admin.jsp?content=group');
        });
    });

    $("#all_groups").unbind('click').click(function() {
        var groups = $("[name='groups']");
        var checked = $('#all_groups').is(':checked');
        for (var i = 0; i < groups.length; i++) {
            $(groups[i]).prop('checked', checked);
        }
    });

    $("#delete_groups_btn").unbind('click').click(function() {
        var groups = $("[name='groups']");

        var ids = 'id=';
        for (var i = 0; i < groups.length; i++) {
            if ($(groups[i]).is(':checked')) {
                console.log($(groups[i]).attr('id'));
                ids += ($(groups[i]).attr('id') + ';');
            }
        }
        ids = ids.substr(0, ids.length - 1);
        var dataString = ids;
        sendData(dataString, "DeleteGroup", function() {
            window.location.replace('admin.jsp?content=group');
        });
    });

    $("#delete_group_btn").unbind('click').click(function() {
        var dataString = 'id=' + $('#group_id').attr('value');
        sendData(dataString, "DeleteGroup", function() {
            window.location.replace('admin.jsp?content=group');
        });
    });

    $("#edit_group_btn").unbind('click').click(function() {
        var idGroup = $('#group_id').attr('value');
        window.location.replace('admin.jsp?content=group&operation=create&id=' + idGroup);
    });

    $("#all_users").unbind('click').click(function() {
        var users = $("[name='users']");
        var checked = $('#all_users').is(':checked');
        for (var i = 0; i < users.length; i++) {
            $(users[i]).prop('checked', checked);
        }
    });

    $("#delete_users_btn").unbind('click').click(function() {
        var users = $("[name='users']");

        var ids = 'id=';
        for (var i = 0; i < users.length; i++) {
            if ($(users[i]).is(':checked')) {
                console.log($(users[i]).attr('id'));
                ids += ($(users[i]).attr('id') + ';');
            }
        }
        ids = ids.substr(0, ids.length - 1);
        var dataString = ids;
        sendData(dataString, "DeleteUser", function() {
            window.location.replace('admin.jsp?content=user');
        });
    });

});

function sendData(dataString, dest, onSuccess) {
    $.ajax({
        type: "POST",
        url: dest,
        data: dataString,
        success: function(response_data) {
            onSuccess(response_data);
        },
        error: function() {
            console.log('error');
        }
    });
}

function edit_user() {
    window.location.replace('admin.jsp?content=user&operation=create&id=' + $('#user_id').attr('value'));
}

function is_illegal_input() {
    if (!validate($('#login').val(), "^[a-zA-Z]\\w{2,}")) {
        console.log('WRONG login');
        return true;
    }
    if (!validate($('#first-name').val(), "^[a-zA-Z]+[a-zA-Z ,.'-]+$")) {
        console.log('WRONG fname');
        return true;
    }
    if (!validate($('#last-name').val(), "^[a-zA-Z]+[a-zA-Z ,.'-]+$")) {
        console.log('WRONG lname');
        return true;
    }
    if (!validate($('#email').val(), "(([A-Za-z])|(\\d)|([-_.]))+@([A-Za-z])+[.]([A-Za-z]){2,4}")) {
        console.log('WRONG email');
        return true;
    }
    if (!validate($('#password').val(), "\\w{6,14}$")) {
        console.log('WRONG pass');
        return true;
    }
    if (!validate($('#latitude').val(), "^[1-9]+[0-9]+([\.\,][0-9]+)?$")) {
        console.log('WRONG latitude');
        return true;
    }
    if (!validate($('#longitude').val(), "^[1-9]+[0-9]+([\.\,][0-9]+)?$")) {
        console.log('WRONG longitude');
        return true;
    }
    if ($('#country').val() == "") {
        return true;
    }
    if ($('#city').val() == "") {
        return true;
    }
    if ($('#street').val() == "") {
        return true;
    }
    if ($('#home').val() == "") {
        return true;
    }
    if ($('#password').val() != $('#confpassword').val()) {
        return true;
    }
    return false;
}

function show_error_dialog() {
    var dialog = '<div id="message"><div id="dark-font"></div>'
                   + '<div id="dialog-outer">' 
                   + '<div id="dialog">' 
                   + '<h1>Error!</h1>' 
                   + 'Some fields has illegal values.'
                   + 'Please, check it.'
                   + '<div style="text-align: center; margin-top: 30px;">' 
                   + '<input type="button" value="Ok" id="ok_btn"/>'
                   + '</div></div></div></div>';
    $("#content").after(dialog);
    $("#ok_btn").click(function() {
        $("#message").remove();
    });
}

function save_created_user() {
    var dataString = 'action=' + action +
            '&login=' + $('#login').val() +
            '&fName=' + $('#first-name').val() +
            '&lName=' + $('#last-name').val() +
            '&email=' + $('#email').val() +
            '&password=' + $('#password').val() +
            '&country=' + $('#country').val() +
            '&city=' + $('#city').val() +
            '&street=' + $('#street').val() +
            '&home=' + $('#home').val() +
            '&appartment=' + $('#appartment').val() +
            '&latitude=' + $('#latitude').prop('value') +
            '&longitude=' + $('#longitude').prop('value');
    if (is_illegal_input()) {
        show_error_dialog();
        return;
    }
    if (action == "edit") {
        dataString += '&userId=' + $('#user_id').attr('value');
    }
    var roles = $('[name="role"]');
    var rlsStr = '&roles=';
    for (var i = 0; i < roles.length; i++) {
        if ($(roles[i]).is(":checked")) {
            rlsStr += $(roles[i]).attr('id') + ';';
        }
    }
    var groups = $('[name="group"]');
    var groupsStr = "&groups=";
    for (var i = 0; i < groups.length; i++) {
        if ($(groups[i]).is(":checked")) {
            groupsStr += $(groups[i]).attr('id') + ';';
        }
    }
    rlsStr = rlsStr.substr(0, rlsStr.length - 1);
    groupsStr = groupsStr.substr(0, groupsStr.length - 1);
    dataString += rlsStr;
    dataString += groupsStr;
    sendData(dataString, "UserOperation", function(data) {
        window.location.replace('admin.jsp?content=user');
    });
}

function delete_user() {
    var dataString = 'id=' + $('#user_id').attr('value');
    sendData(dataString, "DeleteUser", function() {
        window.location.replace('admin.jsp?content=user');
    });
}

function filter_role() {
    var dataString = 'action=content' +
            '&filter=' + $('#select_filter_role :selected').attr('id');
    sendData(dataString, "GroupOperation", function(data) {
        var group_users = $('#group_users option');
        var htmlStr = "";
        for (var i = 0; i < data.length; i++) {
            var flag = true;
            for (var j = 0; j < group_users.length; j++) {
                if ($(group_users[j]).attr('id') == data[i].id) {
                    flag = false;
                }
            }
            if (flag) {
                htmlStr += '<option id='
                htmlStr += '"' + data[i].id + '" >';
                htmlStr += data[i].first + ' ';
                htmlStr += data[i].last + '</option>';
            }
        }
        $('#non_group_users').html(htmlStr);
    });
}

function checkValidate(input, inputErr, pattern) {
    if (!validate(input.val(), pattern)) {
        inputErr.html("Incorrectly input!");
        input.css("border-color", "#ef3124");
        return false;
    } else {
        input.css("border-color", "#79c30c");
        inputErr.html("");
        return true;
    }
}

function validate(value, pattern) {
    var reg = new RegExp(pattern);
    return reg.test(value);
}